package com.xunlai.infra.permission.manager.authority.login;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xunlai.infra.permission.manager.web.vo.BaseResponse;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 成功后返回response body
 * @author yanguoliang
 * @date 2020/8/31 19:52
 */
@Slf4j
public abstract class AbstractResponseBodyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        handleSuccessInternal(request,authentication);
        BaseResponse<Object> result = BaseResponse.success(successBody(request, authentication));
//        result.();
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(result));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    }

    protected abstract void handleSuccessInternal(HttpServletRequest request, Authentication authentication);

    protected abstract Object successBody(HttpServletRequest request, Authentication authentication);

    protected int successCode(HttpServletRequest request, Authentication authentication){
        return AbstractResponseBodyAuthenticationFailureHandler.SUCCESS;
    }

    protected  String successMsg(HttpServletRequest request, Authentication authenticationException) {
        return "success";
    }
}
